package org.example.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.example.domain.Log;
import org.example.dto.UserLoginDTO;
import org.example.result.Result;
import org.example.service.LogService;
import org.example.service.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * @BelongsProject：blockchain-APTrace
 * @CreateTime 2024-05-25-14:38
 * @Author SweetPig
 */
@Component
@Aspect
public class LogAspect {

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private LogService logService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 定义切点
     */
    @Pointcut("@annotation(org.example.annotation.Login))")
    public void loginCutPoint() {
    }

    /**
     * 环绕通知记录日志
     *
     * @param pjp
     * @return
     * @throws Throwable
     */
    @Around("loginCutPoint()")
    public Object point(ProceedingJoinPoint pjp) throws Throwable {

        //获取参数
        Object[] args = pjp.getArgs();
        if (args.length == 0) {
            return null;
        }
        Object proceed = pjp.proceed();
        Result result = (Result) proceed;
        if (result.getCode() == 200) {
            UserLoginDTO arg = (UserLoginDTO) args[0];
            //查询用户所属角色
            Integer roleId = userRoleService.queryUser(arg.getUsername());
            Log log = Log.builder()
                    .ip(request.getRemoteHost())
                    .username(arg.getUsername())
                    .roleId(roleId)
                    .loginTime(LocalDateTime.now()).build();
            logService.saveLog(log);
            
        }
        return proceed;
    }

}
